package MTT::Libs::Masks;

use Moose;

use DBI;

has 'masks' => ( is => 'ro', isa => 'HashRef', writer => 'set_masks' );

sub BUILD {
	my ($self, $args) = @_;
	$self->load($args);

}

sub load {
	my ($self, $args) = @_;

	my $masks = {};

	my $dbh;
	if ( $args->{ctx} || $args->{schema} ) {
		my $schema = $args->{schema} || $args->{ctx}->model('DBIC');
		if ($schema) {
			$dbh = $schema->storage->dbh;
		}
	}
	elsif ( $args->{dbh} ) {
		$dbh = $args->{dbh};
	}

	foreach my $m ( @{ $dbh->selectall_arrayref('SELECT * FROM masks') } ) {
		my @data = @$m;
		shift @data;
		$masks->{ $m->[0] } = \@data; #$m->[1]; #, $m->[2], $m->[3], $m->[4], $m->[5], $m->[6], $m->[7], $m->[8], $m->[9] ];
	}
	
	$self->set_masks($masks);
}

sub get_mask {
	my ($self, $number) = @_;

	return unless $number;

	my $mask;
	my $l = length $number;
	while ( my $subnum = substr $number, 0, $l ) {
		$l--;
		if ($self->masks->{$subnum} ) {
			$mask = $subnum;
			last;
		}
	}

	if ( $mask ) {
		return ( wantarray ? ( $mask, $self->masks->{$mask} ) : $mask );
	}
	return undef;
}

__PACKAGE__->meta->make_immutable;
1;
